use crate::core::protocol::transfer::send_file;
use crate::core::{Command, DeviceInfo};
use log::{error, info};
use std::{collections::HashMap, sync::Arc};
use tokio::sync::{Mutex, mpsc};
pub async fn process(
    devices: Arc<Mutex<HashMap<u64, DeviceInfo>>>,
    mut rx: mpsc::Receiver<Command>,
) {
    while let Some(cmd) = rx.recv().await {
        match cmd {
            Command::ListDevices => {
                let devices = devices.lock().await;
                info!("\n在线设备 ({}):", devices.len());
                for (id, info) in devices.iter() {
                    info!(
                        " - {} [{}] ({}:{}) | 最后活跃: {:.1}秒前",
                        info.name,
                        id,
                        info.ip,
                        info.transfer_port,
                        info.last_seen.elapsed().as_secs_f32()
                    );
                }
            }
            Command::SendFile(device_id, file_path) => {
                if let Some(device) = devices.lock().await.get(&device_id) {
                    if let Err(e) = send_file(&device, &file_path).await {
                        error!("发送文件失败: {}", e);
                    }
                } else {
                    error!("设备 {} 不存在", device_id);
                }
            }
            Command::Help => {
                info!("============ 帮助信息 ============");
                info!("list or ls - 列出所有设备");
                info!("send <设备ID> <文件路径> - 发送文件到指定设备");
                info!("broadcast or b - 广播局域网监听在8888端口的设备");
                info!("search <IP地址> <端口号> - 搜索指定IP地址的设备");
                info!("remove or rm <设备ID> - 删除指定设备, 无ID则删除所有设备");
                info!("clear or c - 清屏");
                info!("quit or q - 退出程序");
                info!("help or h - 显示帮助信息");
                info!("==================================");
            }
            Command::ClearScreen => {
                info!("\x1B[2J\x1B[1;1H");
            }
            Command::Quit => {
                info!("感谢您的使用 miniLanDrop 期待下次再见");
                std::process::exit(0);
            }
            Command::BroadcastDevices => {
                info!("正在搜索局域网设备8888端口 ...")
            }
            Command::RemoveDevice(0) => {
                info!("正在移除所有设备 ...")
            }
            Command::RemoveDevice(device_id) => {
                info!("正在移除设备 {} ...", device_id);
            }
            _ => {}
        }
    }
}
